package xin.codedream.codelog.web.controller.admin;

import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.HtmlUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import xin.codedream.codelog.exception.ArticleException;
import xin.codedream.codelog.model.entity.Article;
import xin.codedream.codelog.model.entity.Category;
import xin.codedream.codelog.model.entity.Logs;
import xin.codedream.codelog.model.entity.User;
import xin.codedream.codelog.model.enums.ArticleStatusEnum;
import xin.codedream.codelog.model.enums.ConstEnum;
import xin.codedream.codelog.model.enums.LogsEnum;
import xin.codedream.codelog.model.enums.ResponseEnum;
import xin.codedream.codelog.model.global.ResponseData;
import xin.codedream.codelog.service.ArticleService;
import xin.codedream.codelog.service.LogsService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * 文章控制器
 *
 * @author NGLSL
 * @date 2018/8/8
 */
@Slf4j
@RequestMapping("/admin/newArticle")
@RestController
public class ArticleController {

    @Resource
    private LogsService logsService;
    @Resource
    private ArticleService articleService;
    @Resource
    private HttpServletRequest request;

    /**
     * 跳转到新建文章页面
     *
     * @param articleId 文章Id
     * @return String
     */
    @GetMapping("/new")
    public ModelAndView newArticle(Long articleId) {
        ModelAndView mv = new ModelAndView("admin/admin_new_article");
        mv.addObject("articleStatusValues", ArticleStatusEnum.values());
        if (Objects.nonNull(articleId)) {
            Article article = articleService.findArticleByArticleId(articleId);
            mv.addObject("article", article);
        }
        return mv;
    }

    /**
     * 获取所有文章
     *
     * @param article 文章数据
     * @return ModelAndView
     */
    @GetMapping("/all")
    public ModelAndView newArticleAll(@ModelAttribute Article article) {
        ModelAndView mv = new ModelAndView("admin/admin_new_article_all");
        mv.addObject("articleStatusValues", ArticleStatusEnum.values());
        mv.addObject("articles", articleService.findAllArticle(article));
        mv.addObject("articleValue", article);
        return mv;
    }

    /**
     * 保存文章
     *
     * @param article    文章数据
     * @param categoryId 目录Id
     * @param postTime   修改时间
     * @param session    Session
     * @return ResponseData
     */
    @PostMapping("/saveArticle")
    public ResponseData saveArticle(@ModelAttribute Article article,
                                    @RequestParam("postTime") String postTime,
                                    @RequestParam("categoryId") Long categoryId,
                                    HttpSession session) {
        ResponseData responseData = new ResponseData(ResponseEnum.POST_ARTICLE_ERROR);
        Article articleByTitle = articleService.findArticleByTitle(article.getArticleTitle());

        // 已存在该文章，并且id不是同一个
        if (Objects.nonNull(articleByTitle) && !Objects.equals(article.getArticleId(),
                articleByTitle.getArticleId())) {
            responseData.setCodeMessage(ResponseEnum.POST_ARTICLE_TITLE_EXIST);
            return responseData;
        }
        User user = (User) session.getAttribute(ConstEnum.USER_SESSION_KEY.getValue());
        article.setUserId(user.getUserId());
        article.setCreateTime(DateUtil.parseDateTime(postTime));
        article.setCategory(new Category(categoryId));
        // 以防万一还存在空格
        article.setArticleUrl(article.getArticleUrl().replace(" ", "-"));
        int articleSummary = Integer.parseInt(ConstEnum.ARTICLE_SUMMARY.getValue());
        // 文章摘要
        String summaryText = HtmlUtil.cleanHtmlTag(article.getArticleContentHtml());
        if (summaryText.length() > articleSummary) {
            summaryText = summaryText.substring(0, articleSummary);
            article.setArticleSummary(summaryText);
        } else {
            article.setArticleSummary(summaryText);
        }
        try {
            if (Objects.nonNull(articleByTitle) && Objects.equals(article.getArticleId(),
                    articleByTitle.getArticleId())) {
                // 更新文章
                boolean postResult = articleService.updateArticleByArticleId(article);
                if (postResult) {
                    responseData.setCodeMessage(ResponseEnum.UPDATE_ARTICLE_SUCCESS);
                    logsService.saveLogInfo(new Logs(LogsEnum.UPDATE_POST_ARTICLE.getMessage(),
                            "文章：[" + article.getArticleTitle() + "]" + ResponseEnum.UPDATE_ARTICLE_SUCCESS.getMessage(),
                            ServletUtil.getClientIP(request)));
                } else {
                    responseData.setCodeMessage(ResponseEnum.UPDATE_ARTICLE_ERROR);
                    logsService.saveLogInfo(new Logs(LogsEnum.UPDATE_POST_ARTICLE.getMessage(),
                            "文章：[" + article.getArticleTitle() + "]" + ResponseEnum.UPDATE_ARTICLE_ERROR.getMessage(),
                            ServletUtil.getClientIP(request)));
                }
            } else {
                // 发表文章
                boolean postResult = articleService.postArticle(article, article.getTags());
                if (postResult) {
                    responseData.setCodeMessage(ResponseEnum.POST_ARTICLE_SUCCESS);
                    logsService.saveLogInfo(new Logs(LogsEnum.TYPE_POST_ARTICLE.getMessage(),
                            "文章：[" + article.getArticleTitle() + "]" + ResponseEnum.POST_ARTICLE_SUCCESS.getMessage(),
                            ServletUtil.getClientIP(request)));
                } else {
                    responseData.setCodeMessage(ResponseEnum.POST_ARTICLE_ERROR);
                    logsService.saveLogInfo(new Logs(LogsEnum.TYPE_POST_ARTICLE.getMessage(),
                            "文章：[" + article.getArticleTitle() + "]" + ResponseEnum.POST_ARTICLE_ERROR.getMessage(),
                            ServletUtil.getClientIP(request)));
                }
            }
        } catch (Exception e) {
            log.info("文章保存失败:", e);
            responseData.setCodeMessage(ResponseEnum.POST_ARTICLE_ERROR);
            logsService.saveLogInfo(new Logs(LogsEnum.TYPE_POST_ARTICLE.getMessage(),
                    "文章：[" + article.getArticleTitle() + "]" + ResponseEnum.POST_ARTICLE_ERROR.getMessage(),
                    ServletUtil.getClientIP(request)));
        }
        return responseData;
    }

    /**
     * 删除文章
     *
     * @param article 文章数据
     * @return ResponseData
     */
    @PostMapping("/removeArticle")
    public ResponseData removeArticle(@ModelAttribute Article article) {
        ResponseData responseData = new ResponseData();
        Article oldArticle = articleService.findArticleByArticleId(article.getArticleId());
        try {
            boolean removeArticleDataResult = articleService.removeArticleData(oldArticle);
            if (removeArticleDataResult) {
                responseData.setCodeMessage(ResponseEnum.DELETE_ARTICLE_SUCCESS);
                logsService.saveLogInfo(new Logs(LogsEnum.TYPE_POST_ARTICLE.getMessage(),
                        "文章：[" + oldArticle.getArticleTitle() + "]" + ResponseEnum.DELETE_ARTICLE_SUCCESS.getMessage(),
                        ServletUtil.getClientIP(request)));
            }
        } catch (ArticleException e) {
            log.error("文章删除失败：", e);
            responseData.setCodeMessage(ResponseEnum.DELETE_ARTICLE_ERROR);
            logsService.saveLogInfo(new Logs(LogsEnum.TYPE_POST_ARTICLE.getMessage(),
                    "文章：[" + oldArticle.getArticleTitle() + "]" + ResponseEnum.DELETE_ARTICLE_ERROR.getMessage(),
                    ServletUtil.getClientIP(request)));
        }
        return responseData;
    }
}
